package com.zenchn.aspect.service;

import com.zenchn.aspect.utils.CriticalOperModuleEnum;
import com.zenchn.model.TSysAccount;
import com.zenchn.model.TSysAccountExample;
import com.zenchn.model.TSysCriticalOperatingLog;
import com.zenchn.service.*;
import com.zenchn.utils.CommonUtils;
import com.zenchn.utils.Ip2RegionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author panbingqi
 * @date 2021-06-01
 */
@Service
public class BuildCriticalOperLogService {

    private static final Logger log = LoggerFactory.getLogger(BuildCriticalOperLogService.class);


    @Resource
    private CriticalOperatingLogService criticalOperatingLogService;

    @Resource
    private RoleService roleService;


    @Resource
    private AccountService accountService;



    /***
     * 通用保存日志
     * @param currAccount  当前操作人信息
     * @param ip  IP
     * @param operModule  操作模块
     * @param operAction  操作动作
     * @param operDetail  操作详情
     * @param memo   备注
     */
    private void saveCriticalOperatingLog(TSysAccount currAccount,String ip,String operModule,String operAction, String operDetail, String memo){
        TSysCriticalOperatingLog operatingLog=new TSysCriticalOperatingLog();
        operatingLog.setLogId(CommonUtils.randomUUID());
        operatingLog.setAccessIp(ip);
        operatingLog.setAccessLocation(Ip2RegionUtils.getCleanAddress(ip));
        operatingLog.setOperTime(LocalDateTime.now());
        operatingLog.setOperAccountId(currAccount.getAccountId());
        operatingLog.setOperAccount(currAccount.getAccount());
        operatingLog.setOperRealName(currAccount.getRealName());
        operatingLog.setOperModule(operModule);
        operatingLog.setOperAction(operAction);
        operatingLog.setOperDetail(operDetail);
        operatingLog.setMemo(memo);
        criticalOperatingLogService.insert(operatingLog);
    }

    @Async
    public void accountDelete(TSysAccount currAccount,String ip ,Map<String, String> pathVariables) throws Exception {
        //获取参数
        String[] accountIds =pathVariables.get("accountIds").split(",");

        TSysAccountExample accountExample=new TSysAccountExample();
        accountExample.createCriteria().andAccountIdIn(Arrays.asList(accountIds));

        String accounts=accountService.selectByExample(accountExample).stream().map(TSysAccount::getAccount).collect (Collectors.joining (","));

        saveCriticalOperatingLog(currAccount,ip,CriticalOperModuleEnum.ACCOUNT_CONTROLLER.getValue(),"删除账户","删除账号["+accounts+"]账户信息",pathVariables.toString());

    }

}
